package com.vhall.component.plugin.common.config;

import com.vhall.component.plugin.common.utils.FastJson2JsonRedisSerialize;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author skeleton
 * @since 2020/8/17
 **/
@Configuration
@ConditionalOnClass(RedisOperations.class)
public class RedisConfig {
    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    @Bean
    public GenericJackson2JsonRedisSerializer genericJackson2JsonRedisJsonSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

    @Bean
    public RedisSerializer fastJson2JsonRedisSerialize() {
        return new FastJson2JsonRedisSerialize<Object>(Object.class);
    }

    @Bean
    public <T> RedisTemplate<String, T> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();
        // GenericJackson2JsonRedisSerializer会序列化对象的类型
        // 因此在重构时需要留意对象的改动
        redisTemplate.setDefaultSerializer(genericJackson2JsonRedisJsonSerializer());
        redisTemplate.setKeySerializer(stringRedisSerializer());
        redisTemplate.setHashKeySerializer(stringRedisSerializer());
//        redisTemplate.setValueSerializer(stringRedisSerializer());

        redisTemplate.setConnectionFactory(factory);

        return redisTemplate;
    }
}
